package serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.codehaus.jackson.map.ObjectMapper;

import domain.SensorData;

public class JsonSerializer implements ISerializer {
	private ObjectMapper mapper = new ObjectMapper();

	public SensorData decode(byte[] buf) {
		try {
			ByteArrayInputStream bis = new ByteArrayInputStream(buf);
			SensorData obj = mapper.readValue(bis, SensorData.class);
			return obj;
		} catch (Exception e) {
			System.err.println("Error occured, while parsing JSON. Details: "
					+ e.getMessage());
		}
		return null;
	}

	public byte[] encode(SensorData obj) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			mapper.writeValue(bos, obj);
			return bos.toByteArray();
		} catch (IOException e) {
			System.err.println("Error occured, while builing JSON. Details: "
					+ e.getMessage());
		}
		return null;
	}

}
